package com.eastfair.pay.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.eastfair.boot.request.PageParams;
import com.eastfair.boot.service.SuperServiceImpl;
import com.eastfair.constant.BusinessConstant;
import com.eastfair.core.base.R;
import com.eastfair.core.context.ContextUtil;
import com.eastfair.core.exception.BizException;
import com.eastfair.core.utils.ConvertUtil;
import com.eastfair.pay.dao.SettlementMapper;
import com.eastfair.pay.dto.InvoiceCallbackDTO;
import com.eastfair.pay.dto.SettlementDetailsSaveDTO;
import com.eastfair.pay.dto.SettlementPageQuery;
import com.eastfair.pay.dto.SettlementSaveDTO;
import com.eastfair.pay.entity.Settlement;
import com.eastfair.pay.entity.SettlementDetails;
import com.eastfair.pay.exceptioncode.PayExceptionCode;
import com.eastfair.pay.service.SettlementDetailsService;
import com.eastfair.pay.service.SettlementService;
import com.eastfair.pay.vo.SettlementDetailsVO;
import com.eastfair.pay.vo.SettlementVO;
import com.eastfair.util.OrderUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.Collection;
import java.util.List;
import java.util.Objects;

/**
 * <p>
 * 业务实现类
 * 结算单
 * </p>
 *
 * @author clm
 * @date 2022-06-08
 */
@Slf4j
@Service
public class SettlementServiceImpl extends SuperServiceImpl<SettlementMapper, Settlement> implements SettlementService {

    @Autowired
    private SettlementDetailsService detailsService;
    /**
     * 处理逻辑删除相关处理
     *
     * @param modelList 实体
     * @return 是否成功
     */
    @Override
    protected R<Boolean> handlerRemoveByIdsOfLogic(Collection<Settlement> modelList) {
        modelList.stream().forEach(s -> {
            s.setIsDeleted(BusinessConstant.YES);
        });
        // TODO: 2021/10/29 这里需要操作其他业务，如清空角色等
        return R.successDef();
    }

    /**
     * 基础数据
     * @param model
     * @return
     */
    @Override
    protected R<Boolean> handlerSave(Settlement model) {
        model.setProjectId(ContextUtil.getProjectId());
        model.setSubsystemId(ContextUtil.getSubSystemId());
        model.setTenantId(ContextUtil.getTenantId());
        //雪花ID
        return R.successDef();
    }

    /**
     * 结算保存
     * @param saveDTO
     * @return
     */
    @Override
    public void settlementSaveDeail(SettlementSaveDTO saveDTO) {

        //订单号
        saveDTO.setSettleNumber(OrderUtil.getOrderNo("JSD"));
        //结算时间
        saveDTO.setSettleTime(LocalDateTime.now());
        //实体转化
        Settlement settlement = new Settlement();
        BeanUtils.copyProperties(saveDTO,settlement);

        settlement.setReturnAmount(settlement.getSpaceBond().add(settlement.getServiceBond()));
        //保存结算单
        save(settlement);
        //实体转化
        List<SettlementDetailsSaveDTO> settlementDetailsList = saveDTO.getDetailsSaveDTOList();
        List<SettlementDetails> detailsList = ConvertUtil.convertList(settlementDetailsList, SettlementDetails.class);
        detailsList.forEach(list->{
            list.setSettlementId(settlement.getId());
            list.setProjectId(ContextUtil.getProjectId());
            list.setSubsystemId(ContextUtil.getSubSystemId());
            list.setTenantId(ContextUtil.getTenantId());
        });
        //保存结算单详情
         detailsService.saveBatch(detailsList);

    }

    /**
     * 分页查询
     * @param params
     * @return
     */
    @Override
    public Page<SettlementVO> queryPageList(PageParams<SettlementPageQuery> params) {

        SettlementPageQuery settlementPageQuery = params.getModel();
        LambdaQueryWrapper<Settlement> settlementLambdaQueryWrapper = new LambdaQueryWrapper<>();
        settlementLambdaQueryWrapper.eq(Settlement::getIsDeleted,0);
//        applyRefundLambdaQueryWrapper.apply("DATE_FORMAT(create_time ,'%Y-%m-%d') <= "+applyRefundPageQuery.getRefundTime());

        //结算时间
        settlementLambdaQueryWrapper.ge(settlementPageQuery.getStartSettleTime()!= null, Settlement::getSettleTime,settlementPageQuery.getStartSettleTime());
        settlementLambdaQueryWrapper.le(settlementPageQuery.getEndSettleTime()!= null,Settlement::getSettleTime,settlementPageQuery.getEndSettleTime());
        //关键字
        settlementLambdaQueryWrapper.and(StrUtil.isNotEmpty(settlementPageQuery.getKeywords()), likeQueryWrapper -> likeQueryWrapper
                .like(Settlement::getExhibitionName, settlementPageQuery.getKeywords())
                .or().like(Settlement::getCutomerName, settlementPageQuery.getKeywords())

        );
        //展会ID
        settlementLambdaQueryWrapper.eq(Objects.nonNull(settlementPageQuery.getExhibitionId()),Settlement::getExhibitionId,settlementPageQuery.getExhibitionId());
        //参数转化
        Page<Settlement> settlementPage =params.buildPage();
        //查询
        Page<Settlement> refundPage = page(settlementPage,settlementLambdaQueryWrapper);
        //实体转化
        Page<SettlementVO> paymentRecordVOPage = ConvertUtil.convertPage(refundPage, SettlementVO.class);
        //金额计算
        List<SettlementVO> settlementVOList =  paymentRecordVOPage.getRecords();
        for (SettlementVO vo:settlementVOList ) {
            vo.setNotInvoiceAmount((vo.getPayableAmount()==null?new BigDecimal(0):vo.getPayableAmount()).subtract((vo.getInvoiceAmount()==null?new BigDecimal(0):vo.getInvoiceAmount())));
        }
        //存储数据
        paymentRecordVOPage.setRecords(settlementVOList);
        return paymentRecordVOPage;
    }

    /**
     * 通过ID查询结算单详情
     * @param settlementId
     * @return
     */
    @Override
    public SettlementVO settlementQueryById(Long settlementId) {
        //查询结算单
        Settlement settlement = getById(settlementId);
        if(null == settlement){
            throw new BizException(PayExceptionCode.SETTLEMEN_DOCUMENT_DOES_NOT_EXIST.getMsg());
        }
        //根据ID查询结算单详情
        QueryWrapper<SettlementDetails> settlementDetailsQueryWrapper = new QueryWrapper<>();
        settlementDetailsQueryWrapper.lambda().eq(SettlementDetails::getSettlementId,settlementId);
        List<SettlementDetails> detailsList = detailsService.list(settlementDetailsQueryWrapper);
        //合计
        BigDecimal totalAmout  = detailsList.stream().map(SettlementDetails::getContractAmount).reduce(BigDecimal.ZERO, BigDecimal::add);
        //结算单实体转化
        SettlementVO vo = new SettlementVO();
        BeanUtils.copyProperties(settlement,vo);
        vo.setId(settlement.getId());
        //结算单详情实体转化
        List<SettlementDetailsVO> settlementDetailsVOS = ConvertUtil.convertList(detailsList, SettlementDetailsVO.class);
        //存储详情
        vo.setDetailsVOList(settlementDetailsVOS);
        vo.setTotalAmout(totalAmout);
        return  vo;
    }

    /**
     * @param invoiceCallbackDTO
     * @return void
     * @Author clm
     * @Description 开票回填
     * @Date 14:52 2022/7/14
     * @Param [invoiceCallbackDTO]
     */
    @Override
    public void updateForInvoice(InvoiceCallbackDTO invoiceCallbackDTO) {
        Settlement settlement = getById(invoiceCallbackDTO.getBusinessId());
        settlement.setInvoiceAmount(invoiceCallbackDTO.getInvoicedAmount());
        updateById(settlement);
    }

}
